package com.ruoyi.web.until;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import org.json.JSONArray;
import org.json.JSONObject;

@SuppressWarnings("unchecked")
public class InvokeHelper {

    // K3 Cloud WebSite URL Example "http://192.168.19.113/K3Cloud/"
    public static String POST_K3CloudURL = "http://222.221.246.154:8085/k3cloud/";

    // Cookie 值
    private static String CookieVal = null;

    private static String AccountId = "60a22dac73e06a";

    private static Map map = new HashMap();
    static {
        map.put("Save",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Submit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("WorkflowAudit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.WorkflowAudit.common.kdsvc");
    }

    // HttpURLConnection
    private static HttpURLConnection initUrlConn(String url, JSONArray paras)
            throws Exception {
        URL postUrl = new URL(POST_K3CloudURL.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        if (CookieVal != null) {
            connection.setRequestProperty("Cookie", CookieVal);
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }

    // HttpURLConnection
    private static HttpURLConnection initUrlConn2(String url, JSONArray paras,String cookie)
            throws Exception {
        URL postUrl = new URL(POST_K3CloudURL.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setRequestProperty("kdservice-sessionid", cookie);
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }

    // HttpURLConnection
    public static HttpURLConnection initUrlConn3(String url, JSONArray paras,String cookie)
            throws Exception {
        URL postUrl = new URL(POST_K3CloudURL.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setRequestProperty("kdservice-sessionid", cookie);
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }

    // Login
    public static boolean Login(String dbId, String user, String pwd, int lang)
            throws Exception {

        boolean bResult = false;

        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

        JSONArray jParas = new JSONArray();
        jParas.put(dbId);// 帐套Id
        jParas.put(user);// 用户名
        jParas.put(pwd);// 密码
        jParas.put(lang);// 语言

        HttpURLConnection connection = initUrlConn(sUrl, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    CookieVal = tempCookieVal;
                    break;
                }
            }
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
            bResult = line.contains("LoginResultType");
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();

        connection.disconnect();

        return bResult;
    }

    public static Map<String, Object> Login2(String dbId, String user, String pwd, int lang)
            throws Exception {

        boolean bResult = false;

        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

        JSONArray jParas = new JSONArray();
        jParas.put(dbId);// 帐套Id
        jParas.put(user);// 用户名
        jParas.put(pwd);// 密码
        jParas.put(lang);// 语言

        HttpURLConnection connection = initUrlConn(sUrl, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    int endIndex = tempCookieVal.indexOf(';');
                    CookieVal = tempCookieVal.substring(20, endIndex);
                    break;
                }
            }
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        com.alibaba.fastjson.JSONObject jsonObject2;
        String msg = null;String username = null;String userid = null;String cid = null;String cname = null;String custname = null;
//        System.out.println(" ============================= ");
//        System.out.println(" Contents of post request ");
//        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
//            System.out.println(sResult);
            jsonObject2 = com.alibaba.fastjson.JSONObject.parseObject(sResult);
            if(jsonObject2.containsKey("Context")) {
                if(jsonObject2.get("Context")!=null) {
                    com.alibaba.fastjson.JSONObject jsonObject3 = jsonObject2.getJSONObject("Context");
                    if (jsonObject3.containsKey("UserId")) {
                        userid = jsonObject3.getString("UserId");
                    }
                    if (jsonObject3.containsKey("UserName")) {
                        username = jsonObject3.getString("UserName");
                    }
                    if (jsonObject3.containsKey("CustomName")) {
                        custname = jsonObject3.getString("CustomName");
                    }
                    if(jsonObject3.containsKey("CurrentOrganizationInfo")){
                        if(jsonObject3.get("CurrentOrganizationInfo")!=null) {
                            com.alibaba.fastjson.JSONObject jsonObject4 = jsonObject3.getJSONObject("CurrentOrganizationInfo");
                            if(jsonObject4.containsKey("ID")){
                                cid = jsonObject4.getString("ID");
                            }
                            if(jsonObject4.containsKey("Name")){
                                 cname = jsonObject4.getString("Name");
                            }
                        }
                    }
                }
            }
            msg = jsonObject2.getString("Message");
//            bResult = line.contains("LoginResultType");
            bResult = jsonObject2.getString("LoginResultType").equals("1");
        }
//        System.out.println(" ============================= ");
//        System.out.println(" Contents of post request ends ");
//        System.out.println(" ============================= ");
        reader.close();

        connection.disconnect();

        Map<String, Object> map = new HashMap<>();
        map.put("msg",msg);
        map.put("cook",DesUtil.encrypt(CookieVal));
//        map.put("cook2",CookieVal);
//        String sdsd = DesUtil.encrypt(CookieVal);
//        map.put("cook3",DesUtil.decrypt(sdsd));
        map.put("userCode",DesUtil.encrypt(user+"\n"+pwd));
        map.put("flag",bResult);
        map.put("username",username);     //用户名称
        map.put("userid",userid);         //用户内码
        map.put("cid",cid);              //员工当前机构内码
        map.put("cname",cname);         //员工当前机构名称
        map.put("custname",custname);   //员工属于机构
        return map;
    }

    public static String getCook()
            throws Exception {

        boolean bResult = false;

        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

        JSONArray jParas = new JSONArray();
        jParas.put("60a22dac73e06a");// 帐套Id
        jParas.put("金小敏");// 用户名
        jParas.put("309622");// 密码
        jParas.put(2052);// 语言

        HttpURLConnection connection = initUrlConn(sUrl, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    int endIndex = tempCookieVal.indexOf(';');
                    CookieVal = tempCookieVal.substring(20, endIndex);
                    break;
                }
            }
        }

        connection.disconnect();
        return CookieVal;
    }

    public static String getUserCook(String userCook) throws Exception {
        boolean bResult = false;
        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
        String userCookVal = DesUtil.decrypt(userCook);
        String[] split = userCookVal.split("\n");
        JSONArray jParas = new JSONArray();
        jParas.put(AccountId);// 帐套Id
        jParas.put(split[0]);// 用户名
        jParas.put(split[1]);// 密码
        jParas.put(2052);// 语言

        HttpURLConnection connection = initUrlConn(sUrl, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    int endIndex = tempCookieVal.indexOf(';');
                    CookieVal = tempCookieVal.substring(20, endIndex);
                    break;
                }
            }
        }

        connection.disconnect();
        return CookieVal;
    }

    // Save
    public static com.alibaba.fastjson.JSONObject Save(String formId, String content, String cook) throws Exception {
        return Invoke2("Save", formId, content,cook);
    }

//    // View
//    public static void View(String formId, String content) throws Exception {
//        Invoke("View", formId, content);
//    }
//
    // Submit
    public static com.alibaba.fastjson.JSONObject Submit(String formId, String content, String cook) throws Exception {
        return Invoke2("Submit", formId, content,cook);
    }

    // Audit
    public static com.alibaba.fastjson.JSONObject Audit(String formId, String content,String cook) throws Exception {
        return Invoke2("Audit", formId, content,cook);
    }

    // UnAudit
    public static com.alibaba.fastjson.JSONObject UnAudit(String formId, String content,String cook) throws Exception {
        return Invoke2("UnAudit", formId, content,cook);
    }

    // WorkflowAudit
    public static com.alibaba.fastjson.JSONObject WorkflowAudit(String formId, String content,String cook) throws Exception {
        return Invoke3("WorkflowAudit", formId, content,cook);
    }
//
//    // StatusConvert
//    public static void StatusConvert(String formId, String content)
//            throws Exception {
//        Invoke("StatusConvert", formId, content);
//    }

    private static void Invoke(String deal, String formId, String content,String cook)
            throws Exception {

        String sUrl = map.get(deal).toString();
        JSONArray jParas = new JSONArray();
        jParas.put(formId);
        jParas.put(content);

        HttpURLConnection connectionInvoke = initUrlConn2(sUrl, jParas,cook);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));

        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
            
            System.out.println(sResult);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();

        connectionInvoke.disconnect();
    }


    public static com.alibaba.fastjson.JSONObject Invoke2(String deal, String formId, String content, String cook)
            throws Exception {

        String sUrl = map.get(deal).toString();
        JSONArray jParas = new JSONArray();
        jParas.put(formId);
        jParas.put(content);

        HttpURLConnection connectionInvoke = initUrlConn2(sUrl, jParas,cook);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));

        String line;
        String sResult = null;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();

        connectionInvoke.disconnect();
        return JSON.parseObject(sResult);
    }

    public static com.alibaba.fastjson.JSONObject Invoke3(String deal, String formId, String content, String cook)
            throws Exception {

        String sUrl = map.get(deal).toString();
        JSONArray jParas = new JSONArray();
        //jParas.put(formId);
        jParas.put(JSON.parseObject(content));

        HttpURLConnection connectionInvoke = initUrlConn2(sUrl, jParas,cook);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));

        String line;
        String sResult = null;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();

        connectionInvoke.disconnect();
        return JSON.parseObject(sResult);
    }

    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }
}